#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from django import forms
from blogmaker import util
from django.utils.translation import ugettext as _
from django.conf import settings
import datetime
from models import Comment
from models import Comment
from django.utils.html import strip_tags
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site

class PublicCommentForm(forms.Form):
    "Manipulator that handles public free (unregistered) comments"
    person_name  = forms.CharField(max_length = 50)
    person_email = forms.CharField(max_length = 75, required = False)
    person_www   = forms.CharField(max_length = 200, required = False)
    comment      = forms.CharField(max_length = 3000, required= True, widget = forms.Textarea)

    def clean_person_name(self):
        #TODO add noProfaties and text_only
        value = self.cleaned_data["person_name"]
        self.text_only(value)
        return value

    def clean_person_email(self):
        #TODO add noprofanieties and text_only
        value = self.cleaned_data["person_email"]
        self.text_only(value)
        return value

    def clean_person_www(self):
        #TODO no profanities and safe link
        value = self.cleaned_data['person_www']
        self.text_only(value)
        self.is_safe_html(value)
        if not util.is_safe_html('<a href="%s">%s</a>' % (value, self.cleaned_data['person_name'])):
            # Prevent JS injection, e.g. person_www = " onMouseover="alert('This is a Javascript Alert')"
            raise forms.ValidationError(_('Only valid HTTP URLs are allowed here.'))
        return value

    def clean_comment(self):
        value = self.cleaned_data['comment'].strip()
        if value=="":
            raise forms.ValidationError(_('Your comment must not be blank'))
        return strip_tags(value)


    def hasNoProfanities(self, field_data, all_data):
        #TODO Comprovar que funciona
        if settings.COMMENTS_ALLOW_PROFANITIES:
            return
        #return forms.hasNoProfanities(field_data, all_data)
       
    def is_safe_html(self, field_data):
        if not util.is_safe_html(field_data):
            raise forms.ValidationError(_('Only the tags <a> <b> <i> and <p> are allowed here.'))
            
    def text_only(self, field_data):
        if strip_tags(field_data) != field_data:
            raise forms.ValidationError(_('HTML tags are not allowed here.'))

    
    def get_comment(self, new_data):
        "Helper function"
        return Comment(content_type=ContentType.objects.get(pk=new_data["content_type_id"]),
            object_id=new_data["object_id"], comment=new_data["comment"].strip(),
            person_name=new_data["person_name"].strip(), person_email=new_data["person_email"].strip(), 
            person_www=new_data["person_www"].strip(), 
            submit_date=datetime.datetime.now(), is_public=new_data["is_public"],
            ip_address=new_data["ip_address"], site=Site.objects.get(id=settings.SITE_ID), 
            comment_type='comment')

    def save(self, new_data):
        today = datetime.date.today()
        c = self.get_comment(new_data)
        # Check that this comment isn't duplicate. (Sometimes people post
        # comments twice by mistake.) If it is, fail silently by pretending
        # the comment was posted successfully.
        for old_comment in Comment.objects.filter(content_type__id__exact=new_data["content_type_id"],
            object_id__exact=new_data["object_id"], person_name__exact=new_data["person_name"],
            submit_date__year=today.year, submit_date__month=today.month,
            submit_date__day=today.day):
            if old_comment.comment == c.comment:
                return old_comment
        c.save()
        return c


